<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FormData文件上传</title>
    <style>
        .progress {
            width: 900px;
            height: 20px;
            background-color: #F2F2F2;
            text-align: center;
            border-radius: 8px;
        }
        
        .progress-bar {
            background-color: #2ECCFA;
            color: white;
            border-radius: 8px;
            box-sizing: content-box;
        }
    </style>
</head>

<body>
    <input type="file" id='file'>
    <div class='progress'>
        <div class='progress-bar' style='width:0%' id='bar'>0%</div>
    </div>
    <div id='box'></div>
    <script>
        var file = document.getElementById('file');
        var bar = document.getElementById('bar');
        var box = document.getElementById('box');
        file.onchange = function() {
            // 创建空的formData表单对象
            var formData = new FormData();
            // 将用户选择的文件追加到formData表单对象中
            formData.append('attrName', this.files[0]);
            var xhr = new XMLHttpRequest();
            xhr.open('post', '/upload');
            // 在文件上传的过程中触发
            xhr.upload.onprogress = function(ev) {
                // ev.loaded文件上传了多少
                // ev.total 文件上传的总大小
                var result = (ev.loaded / ev.total) * 100 + '%';
                // 设置进度条的宽度
                bar.style.width = result;
                bar.innerHTML = result;
            };
            xhr.send(formData);
            xhr.onload = function() {
                if (xhr.status == 200) {
                    var result = JSON.parse(xhr.responseText);
                    // 动态创建img表单
                    var img = document.createElement('img');
                    img.src = result.path;
                    // 当图片加载完成以后
                    img.onload = function() {
                        box.appendChild(img);
                    }
                }
            }
        }
    </script>
</body>

</html>